package com.example.demo.shiro;

import com.example.demo.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * Created by hly on 2018\11\14 0014.
 * 对密码进行迭代加密，保证用户密码的安全
 */
public class PasswordHelper {
    //安全的随机字符
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    //算法名称
    public static final String ALGORITHM_NAME = "md5";
    //迭代次数
    public static final int HASH_ITERATIONS = 2;

    public void encryptPassword(User user) {
        //随机字符串作为用户的Salt
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
        //算法、用户密码、用户Salt、迭代次数
        String newPassword = new SimpleHash(ALGORITHM_NAME,user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),HASH_ITERATIONS).toHex();
        //对用户设置新密码
        user.setPassword(newPassword);
    }


}
